package cn.asura.otherChat.thread;

import cn.asura.otherChat.util.ClientTool;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.SocketException;

/**
 * 专门读取信息的线程
 */
public class ClientThread implements Runnable {

    private final Socket socket;
    private final String username;

    public ClientThread(Socket socket, String username) {
        this.socket = socket;
        this.username = username;
    }

    @Override
    public void run() {
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            while (true) {
                // 从服务器获取信息
                String msg = bufferedReader.readLine();

                if (msg == null) {
                    break;
                }
                if ("file".equalsIgnoreCase(msg)) {
                    // 接收文件
                    String fileName = bufferedReader.readLine();
                    if ("fail".equalsIgnoreCase(fileName)) {
                        System.out.println("下载失败: 文件不存在");
                    } else {
                        ClientTool.receiveFileFromServer(socket, new File("./storage/client/" + username + "/" + fileName));
                    }
                } else {
                    // 打印信息到控制台
                    System.out.println(msg);
                }
            }
        } catch (SocketException e) {
            System.out.println("关闭 Socket: " + e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
